import * as mqtt from "mqtt/dist/mqtt.min.js";
import toolRandom from "./tool-random";

let cache = {};

function init(url, username, password) {
  if (cache[url]) {
    return cache[url];
  }

  const subList = {};
  // 创建客户端实例
  const options = {
    // Clean session
    clean: true,
    connectTimeout: 4000,
    // 认证信息
    clientId: toolRandom.randomStr(18),
    username,
    password,
  };
  const client = mqtt.connect(url, options);

  client.on("connect", function () {
    console.log("mqtt 服务链接成功...");
  });

  // 接收消息
  client.on("message", function (topic, message) {
    console.log(topic, message.toString());
    if (subList[topic]) {
      subList[topic](message);
    }
  });

  return (cache[url] = {
    /**
     * 订阅消息
     * @param {主题} topic
     * @param {函数} fun
     */
    subscribe(topic, fun) {
      subList[topic] = fun;
      client.subscribe(topic);
    },
    /**
     * 取消订阅
     * @param {主题} topic
     */
    unsubscribe(topic) {
      delete subList[topic];
    },
    /**
     * 取消全部订阅
     */
    unsubscribeAll() {
      Object.keys(subList).forEach((key) => {
        delete subList[key];
      });
    },
    /**
     * 发布消息
     * @param {消息} msg
     */
    publish(msg) {
      client.publish(msg);
    },
  });
}

export function initDefault() {
  return init("wss://lj.zzfmhb.com:12081/ws", "com_server", "com_server");
  // return init("ws://61.52.247.249:12022/mqtt", "com_server", "com_server");
}

export default init;
